package com.huitongmaoyi.ai.dao;

import com.huitongmaoyi.ai.UserSessionHandler;
import com.huitongmaoyi.ai.entity.ChatMessage;
import com.huitongmaoyi.ai.entity.ChatRoom;
import com.huitongmaoyi.ai.util.DBUtil;
import com.huitongmaoyi.ai.util.OnlineUserManager;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 聊天室数据访问类
 */
public class ChatRoomDAO {



    /**
     * 添加成员到聊天室
     */
    public void addMember(long roomId, long userId, boolean isAdmin) throws SQLException {
        String sql = "INSERT INTO chat_room_members (room_id, user_id, is_admin) " +
                "VALUES (?, ?, ?)";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setLong(1, roomId);
            stmt.setLong(2, userId);
            stmt.setBoolean(3, isAdmin);
            stmt.executeUpdate();
        } finally {
            DBUtil.closeConnection();
        }
    }

    /**
     * 根据ID获取聊天室信息
     */
    public ChatRoom getChatRoomById(long roomId) throws SQLException {
        String sql = "SELECT * FROM chat_rooms WHERE room_id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setLong(1, roomId);
            ResultSet rs = stmt.executeQuery();

            if (rs.next()) {
                ChatRoom room = new ChatRoom();
                room.setRoomId(rs.getLong("room_id"));
                room.setRoomName(rs.getString("room_name"));
                room.setCreatorId(rs.getLong("creator_id"));
                room.setCreatedAt(rs.getTimestamp("created_at").toLocalDateTime());
                room.setPrivate(rs.getBoolean("is_private"));
                room.setPassword(rs.getString("password"));
                return room;
            }
            return null;
        } finally {
            DBUtil.closeConnection();
        }
    }

    // 以下是已有的其他方法（保持不变）
    /**
     * 检查用户是否在聊天室中（适配原isMember调用）
     */
    public boolean isMember(long roomId, Long userId, String customerId) throws SQLException {
        if (userId != null) {
            return isUserInRoom(roomId, userId);
        }
        return false;
    }

    /**
     * 检查用户是否在聊天室中
     */
    public boolean isUserInRoom(long roomId, long userId) throws SQLException {
        String sql = "SELECT 1 FROM chat_room_members WHERE room_id = ? AND user_id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setLong(1, roomId);
            stmt.setLong(2, userId);
            ResultSet rs = stmt.executeQuery();
            return rs.next();
        } finally {
            DBUtil.closeConnection();
        }
    }

    /**
     * 发送聊天室消息
     */
    public void sendRoomMessage(long roomId, String senderType, String senderId, String content) throws SQLException {
        String sql = "INSERT INTO chat_messages (room_id, sender_type, sender_id, content, sent_at, is_read) " +
                "VALUES (?, ?, ?, ?, NOW(), FALSE)";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setLong(1, roomId);
            stmt.setString(2, senderType);
            stmt.setString(3, senderId);
            stmt.setString(4, content);
            stmt.executeUpdate();
        } finally {
            DBUtil.closeConnection();
        }
    }

    /**
     * 获取聊天室名称
     */
    public String getRoomName(long roomId) throws SQLException {
        String sql = "SELECT room_name FROM chat_rooms WHERE room_id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setLong(1, roomId);
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                return rs.getString("room_name");
            }
            return "未知聊天室";
        } finally {
            DBUtil.closeConnection();
        }
    }

    /**
     * 获取聊天室所有在线成员的用户名
     */
    // 修改ChatRoomDAO.java中的getOnlineMembers方法
    public List<String> getOnlineMembers(long roomId) throws SQLException {
        List<String> onlineMembers = new ArrayList<>();
        String sql = "SELECT u.username FROM chat_room_members m " +
                "JOIN users u ON m.user_id = u.id " +
                "WHERE m.room_id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setLong(1, roomId);
            ResultSet rs = stmt.executeQuery();

            // 直接使用UserSessionHandler中的在线用户集合
            while (rs.next()) {
                String username = rs.getString("username");
                if (UserSessionHandler.onlineUsers.containsKey(username)) {
                    onlineMembers.add(username);
                }
            }
        } finally {
            DBUtil.closeConnection();
        }
        return onlineMembers;
    }

    /**
     * 获取用户加入的聊天室
     */
    public List<ChatRoom> getUserRooms(long userId) throws SQLException {
        List<ChatRoom> rooms = new ArrayList<>();
        String sql = "SELECT r.* FROM chat_rooms r " +
                "JOIN chat_room_members m ON r.room_id = m.room_id " +
                "WHERE m.user_id = ? ORDER BY r.created_at DESC";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setLong(1, userId);
            ResultSet rs = stmt.executeQuery();
            while (rs.next()) {
                ChatRoom room = new ChatRoom();
                room.setRoomId(rs.getLong("room_id"));
                room.setRoomName(rs.getString("room_name"));
                room.setCreatorId(rs.getLong("creator_id"));
                room.setCreatedAt(rs.getTimestamp("created_at").toLocalDateTime());
                room.setPrivate(rs.getBoolean("is_private"));
                rooms.add(room);
            }
        } finally {
            DBUtil.closeConnection();
        }
        return rooms;
    }
    // 在ChatRoomDAO中添加以下方法
    /**
     * 创建聊天室
     */
    public long createChatRoom(String roomName, long creatorId, boolean isPrivate, String password) throws SQLException {
        String sql = "INSERT INTO chat_rooms (room_name, creator_id, is_private, password) " +
                "VALUES (?, ?, ?, ?)";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS)) {
            stmt.setString(1, roomName);
            stmt.setLong(2, creatorId);
            stmt.setBoolean(3, isPrivate);
            stmt.setString(4, password);
            stmt.executeUpdate();

            ResultSet rs = stmt.getGeneratedKeys();
            if (rs.next()) {
                return rs.getLong(1);
            }
            throw new SQLException("创建聊天室失败，未获取到ID");
        } finally {
            DBUtil.closeConnection();
        }
    }

    /**
     * 获取所有公开聊天室
     */
    public List<ChatRoom> getPublicRooms() throws SQLException {
        List<ChatRoom> rooms = new ArrayList<>();
        String sql = "SELECT * FROM chat_rooms WHERE is_private = FALSE ORDER BY created_at DESC";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            ResultSet rs = stmt.executeQuery();
            while (rs.next()) {
                ChatRoom room = new ChatRoom();
                room.setRoomId(rs.getLong("room_id"));
                room.setRoomName(rs.getString("room_name"));
                room.setCreatorId(rs.getLong("creator_id"));
                room.setCreatedAt(rs.getTimestamp("created_at").toLocalDateTime());
                room.setPrivate(rs.getBoolean("is_private"));
                rooms.add(room);
            }
        } finally {
            DBUtil.closeConnection();
        }
        return rooms;
    }
}